--
-- Author: gnar
-- Date: 2015-12-28 10:58:55
--
local HttpRequest = {}

function HttpRequest.open(args)
	local addr = args.addr or SERVER_ADDR
	local mode = args.mode or "GET"
	local sendStr = args.sendStr
	local callback = args.callback 

	local xhr = cc.XMLHttpRequest:new()
    xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING
    xhr:open(mode, addr)

    local function onReadyStateChange()
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
        	local resp = json.decode(xhr.response)
        	if callback then callback(true,resp) end
        else
        	if callback then callback(false) end
            print("Net:Luanch fail, http state:%d, status:%d", xhr.readyState, xhr.status)
        end
        xhr:unregisterScriptHandler()
    end

    xhr:registerScriptHandler(onReadyStateChange)
    xhr:send(sendStr)
end

function HttpRequest.launch(webSocket) --需要获得 sessionid才允许进行websocket连接

    local args = {}
    args.addr = "http://" .. SERVER_ADDR .. "/game2?action=launcher.getsessionid"
    args.mode = "GET"
    print("http adr:",args.addr)
    local _startWebSocket = function(isHttpSuccess,resp)
            print("http call:",isHttpSuccess)
            if isHttpSuccess then
                webSocket = webSocket or require("app.models.network.WebSocket"):getInstance()
                webSocket:startWithHttp(resp)
            end
    end
    args.callback = _startWebSocket

    HttpRequest.open(args)

end




return HttpRequest

